﻿Function Get-PlexVideo 
{
[CmdletBinding(DefaultParameterSetName="VideoMeta")]
Param(
[Parameter(Mandatory=$True,Position=1)]
    [string]$PlexServer,

[Parameter(Mandatory=$False)]
[ValidateSet('Watched','Unwatched','All')]
[string]$ViewedStatus = 'All',

[Parameter(Mandatory=$False)]
[string]$VideoName,

[Parameter(Mandatory=$False)]
[string]$ShowName,

[Parameter(Mandatory=$False, ParameterSetName="VideoMeta")]
[ValidateSet('TV','Movies')]
[string]$VideoType,

[Parameter(Mandatory=$False, ParameterSetName="TVMeta")]
[int]$SeriesNumber,

[Parameter(Mandatory=$False, ParameterSetName="TVMeta")]
[int]$EpisodeNumber



)

If($PlexServer) #User specified their Plex Server
    {
    $SearchResult = @()
    
    
    Switch ($ViewedStatus.ToLower())
        {
            'all' {$moviesearchtrail = '/search?type=1&sort=titleSort:asc' ; $episodesearchtrail = '/all?type=4&sort=index:asc'}
            'watched' {$moviesearchtrail = '/search?type=1unwatched=0&sort=titleSort:asc' ; $episodesearchtrail = '/all?type=4&unwatched=0&sort=index:asc'}
            'unwatched' {$moviesearchtrail = '/all?type=1&unwatched=1&sort=titleSort:asc' ; $episodesearchtrail = '/all?type=4&unwatched=1&sort=index:asc'}
        }


    If ($EpisodeNumber) {$episodesearchtrail =$episodesearchtrail + "&index=" + $EpisodeNumber}


    If ($VideoName -and (!$EpisodeNumber -or !$SeriesNumber -or !$ShowName)) #Video Name specified as a parameter, no TVMeta parameters defined
        {$moviesearchtrail = $moviesearchtrail + "&title=" + ($VideoName -replace " ","%20"); $episodesearchtrail = $episodesearchtrail + "&title=" + ($VideoName -replace " ","%20")}


        $SectionsBaseURL = "http://" + $PlexServer + ":32400/library/sections"
        $Sections = New-Object System.Xml.XmlDocument
        $Sections.Load($SectionsBaseURL)
        $SectionsDirectories = $Sections.MediaContainer.Directory
        

        If (!$VideoType)
            {#No VideoType or VideoName specified - Global Search
              
              

              ForEach ($Directory in $SectionsDirectories) #Each directory in section listing...
                {
                If ($Directory.Type -eq 'movie') #... where it's a movie
                    {
                    $ChosenLibraryURL = $SectionsBaseURL+ "/" + $Directory.key + $moviesearchtrail #List 'movies' against the section
                    $ChosenLibrary = New-Object System.Xml.XmlDocument
                    $ChosenLibrary.Load($ChosenLibraryURL)
                    ForEach ($Video in ($ChosenLibrary.MediaContainer.Video)) {$SearchResult += $Video}
                    }#Close section type -eq Movie check if block

                ElseIf ($Directory.Type -eq 'show') #... where it's a show
                    {
                    $ChosenLibraryURL = $SectionsBaseURL+ "/" + $Directory.key + $episodesearchtrail #Perform an 'show' search against the section
                    $ChosenLibrary = New-Object System.Xml.XmlDocument
                    $ChosenLibrary.Load($ChosenLibraryURL)
                    ForEach ($Video in ($ChosenLibrary.MediaContainer.Video)) {$SearchResult += $Video}
                    } #Close section type -eq show check if block
                } #Close directory in section loop

        


            
            }#Close ElseIf No VideoType or VideoName specified 

        Else #VideoType initialised
                {
            

                If ($VideoType.ToLower() -eq "movies") #No VideoName, VideoType -eq movie
                     {
                     ForEach ($Directory in $SectionsDirectories) #Each directory in section listing...
                        {
                        If ($Directory.Type -eq 'movie') #... where it's a movie
                            {
                            $ChosenLibraryURL = $SectionsBaseURL+ "/" + $Directory.key + $moviesearchtrail #List 'movies' against the section
                            $ChosenLibrary = New-Object System.Xml.XmlDocument
                            $ChosenLibrary.Load($ChosenLibraryURL)
                            ForEach ($Video in ($ChosenLibrary.MediaContainer.Video)) {$SearchResult += $Video}
                            }#Close section type -eq Movie check if block
                        } #Close directory in section loop
            
                    }# Close No VideoName, VideoType -eq Movie ElseIf block
        
                 ElseIf ($VideoType.ToLower() -eq "tv") #No VideoName, VideoType -eq tv
                    {
                    ForEach ($Directory in $SectionsDirectories) #Each directory in section listing...
                        {
                        If ($Directory.Type -eq 'show') #... where it's a show
                            {
                            $ChosenLibraryURL = $SectionsBaseURL+ "/" + $Directory.key + $episodesearchtrail #Perform an 'show' search against the section
                            $ChosenLibrary = New-Object System.Xml.XmlDocument
                            $ChosenLibrary.Load($ChosenLibraryURL)
                            ForEach ($Video in ($ChosenLibrary.MediaContainer.Video)) {$SearchResult += $Video}
                            } #Close section type -eq show check if block
                        } #Close directory in section loop
           
                    } # Close No VideoName, VideoType -eq TV If block


                }#Close loop where VideoType initialised


        
    If ($SeriesNumber) {$SearchResult = $SearchResult | Where {$_.parentIndex -eq $SeriesNumber}}
    If ($VideoName -and ($EpisodeNumber -or $SeriesNumber -or $ShowName)){$SearchResult = $SearchResult | Where {$_.title -match $VideoName} }
    If ($ShowName) {$SearchResult = $SearchResult | Where {($_.grandparentTitle -match $ShowName) -and ($_.Type -eq 'episode')}}
   

    Return $SearchResult
    }

Else {Write-Error -Message "No Plex Server specified"} #User did not specify their Plex Server
}


Function Get-PlexShow
{

Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$PlexServer,

[Parameter(Mandatory=$False)]
[string]$ShowName,

[Parameter(Mandatory=$False)]
[ValidateSet('Part-Watched','Watched','Unwatched','All')]
[string]$ViewedStatus = 'All'
)

If($PlexServer) #User specified their Plex Server
    {
    $SearchResult = @()
    

    Switch ($ViewedStatus.ToLower())
        {
            'all' {$showsearchtrail = '/all?type=2&sort=titleSort:asc'}
            'watched' {$showsearchtrail = '/all?type=2&sort=titleSort:asc'}
            'part-watched' {$showsearchtrail = '/all?type=2&sort=titleSort:asc'}
            'unwatched' {$showsearchtrail = '/all?type=2&unwatchedLeaves=1&sort=titleSort:asc'}
        }

If ($ShowName) {$showsearchtrail = $showsearchtrail + "&title=" + ($ShowName -replace " ","%20")}

        $SectionsBaseURL = "http://" + $PlexServer + ":32400/library/sections"
        $Sections = New-Object System.Xml.XmlDocument
        $Sections.Load($SectionsBaseURL)
        $SectionsDirectories = $Sections.MediaContainer.Directory

                ForEach ($Directory in $SectionsDirectories) #Each directory in section listing...
                    {


                    If ($Directory.Type -eq 'show') #... where it's of type show
                        {
                        $ChosenLibraryURL = $SectionsBaseURL+ "/" + $Directory.key + $showsearchtrail #Perform an 'show' search against the section
                        $ChosenLibrary = New-Object System.Xml.XmlDocument
                        $ChosenLibrary.Load($ChosenLibraryURL)
                        ForEach ($Show in ($ChosenLibrary.MediaContainer.Directory)) {$SearchResult += $Show}
                        } #Close section type -eq show check if block
                    } #Close directory in section loop
            

If ($ViewedStatus.ToLower() -eq 'part-watched'){$SearchResult = $SearchResult | Where {($_.viewedLeafCount -ne 0) -and ($_.leafCount -ne $_.viewedLeafCount)} }     
ElseIf ($ViewedStatus.ToLower() -eq 'watched'){$SearchResult = $SearchResult | Where {$_.leafCount -eq $_.viewedLeafCount} }            
Return $SearchResult
}

Else {Write-Error -Message "No Plex Server specified"} #User did not specify their Plex Server
}



Function Set-PlexViewedStatus
{
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$PlexServer,

[Parameter(Mandatory=$True,ValueFromPipeline=$true,Position=0)]
[PSobject[]]$Key,

[Parameter(Mandatory=$True)]
[ValidateSet('Watched','Unwatched')]
[string]$ViewedStatus
)

BEGIN {
If ($ViewedStatus.ToLower() -eq "watched") {$ScrobbleAction = "scrobble"}
Else {$ScrobbleAction = "unscrobble"}
}

PROCESS {
ForEach ($ObjectKey in $Key)
{
If ($ObjectKey.GetType().Name -eq 'XmlElement') 
    {
    If ($ObjectKey.ratingKey){$ResolvedObjectKey = $ObjectKey.ratingKey}
    }

ElseIf ($ObjectKey.GetType().Name -eq 'String')
    {
    $ResolvedObjectKey = $ObjectKey
    }

$ScrobbleURL = "http://"+ $PlexServer + ":32400/:/" + $ScrobbleAction + "?key=" + $ResolvedObjectKey + "&identifier=com.plexapp.plugins.library"
$InvokeScrobbleAction = Invoke-WebRequest($ScrobbleURL)
}


}
END {}
}



